<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="就诊日期" prop="visitDate">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        />
      </el-form-item>
      <el-form-item label="科室" prop="departmentId">
        <el-select v-model="queryParams.departmentId" placeholder="所属科室" class="full-width">
          <el-option
            v-for="item in option"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 状态过滤 -->
    <el-radio-group v-model="queryParams.status" style="margin-bottom: 15px;" @change="handleQuery">
      <el-radio-button label="">全部</el-radio-button>
      <el-radio-button label="0">待就诊</el-radio-button>
      <el-radio-button label="1">已就诊</el-radio-button>
      <el-radio-button label="2">已取消</el-radio-button>
    </el-radio-group>

    <el-table v-loading="loading" :data="appointmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="患者姓名" align="center" prop="name"/>
      <el-table-column label="就诊卡号" align="center" prop="cardNo"/>
      <el-table-column label="身份证号" align="center" prop="idCard"/>
      <el-table-column label="手机号码" align="center" prop="phone"/>
      <el-table-column label="就诊科室" align="center" prop="departmentName"/>
      <el-table-column label="挂号类型" align="center" prop="registrationType"/>
      <el-table-column label="挂号费用" align="center" prop="registrationFee">
        <template slot-scope="scope">
          ¥{{ scope.row.registrationFee }}
        </template>
      </el-table-column>
      <el-table-column label="就诊状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '0'" type="warning">待就诊</el-tag>
          <el-tag v-else-if="scope.row.status === '1'" type="success">已就诊</el-tag>
          <el-tag v-else-if="scope.row.status === '2'" type="info">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="就诊日期" align="center" prop="visitDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.visitDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="候诊时间" align="center" prop="htime" width="100"/>
      <el-table-column label="预约时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleView(scope.row)"
          >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--  ***************************************************************************************************  -->
    <!-- 查看预约挂号详情对话框 -->
    <el-dialog title="预约详情" :visible.sync="openView" width="1000px" append-to-body>
      <!-- 体检人信息 -->
      <div class="detail-section">
        <div class="section-title">体检人信息</div>
        <el-row :gutter="24">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">患者姓名</span>
              <span class="value">{{ form.name }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">就诊卡号</span>
              <span class="value">{{ form.card_no }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">证件类型</span>
              <span class="value">身份证号</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">证件号码</span>
              <span class="value">{{ form.id_card }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">手机号码</span>
              <span class="value">{{ form.phone }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">关系</span>
              <span class="value">{{ getRelationType(form.relation) }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <div class="info-item">
              <span class="label">就诊人地址</span>
              <span class="value">{{ form.address }}</span>
            </div>
          </el-col>
        </el-row>

      </div>

      <!-- 预约信息 -->
      <div class="detail-section">
        <div class="section-title">预约信息</div>
        <el-row :gutter="24">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">就诊医院</span>
              <span class="value">{{ formApp.hospitalName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">医院地址</span>
              <span class="value">{{ formApp.hospitalAddressName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">报道科室</span>
              <span class="value">{{ formApp.departmentName }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">就诊医生</span>
              <span class="value">{{ formApp.doctorName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">医生职称</span>
              <span class="value">{{ formApp.jobTitleName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">挂号类型</span>
              <span class="value">{{ formApp.registrationType }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">门诊时间</span>
              <span class="value">{{ form.period }} {{ form.htime }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">候诊时间</span>
              <span class="value">{{ form.htime || '现场排号' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">挂号费</span>
              <span class="value">¥{{ form.registrationFee }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">预约时间</span>
              <span class="value">{{ form.visitDate }}</span>
            </div>
          </el-col>

          <el-col :span="8">
            <div class="info-item">
              <span class="label">状态</span>
              <span class="value">
                <el-tag v-if="form.status === '0'" type="warning">待就诊</el-tag>
                <el-tag v-else-if="form.status === '1'" type="success">已就诊</el-tag>
                <el-tag v-else-if="form.status === '2'" type="info">已取消</el-tag>
              </span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">取消原因</span>
              <span class="value">{{ form.cancelReason || '操作失误' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">取消时间</span>
            <span class="value">{{ form.cancelTime }}</span>
          </div>
        </el-col>
        <el-row :gutter="24">
          <el-col :span="24">
            <div class="info-item">
              <span class="label">预约备注</span>
              <span class="value">{{ form.remark || '请输入内容' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-if="form.status === '2'">
          <el-col :span="24">
            <div class="info-item">
              <el-button type="primary" @click="viewReport">查看报告</el-button>
            </div>
          </el-col>
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAppointment, listDepartment, getAppointment } from '@/api/system/appointment'
import { getPatient } from '@/api/system/patient'
import options from '@/utils/dict/DictOptions'
import { getdepartmentA } from '@/api/system/department'

export default {
  name: 'Appointment',
  computed: {
    options() {
      return options
    }
  },
  dicts: ['sys_normal_disable', 'appointment_type', 'appointment_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预约挂号表格数据
      appointmentList: [],
      // 科室选项
      departmentOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查看详情弹出层
      openView: false,
      // 日期范围
      dateRange: [],
      option: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        beginVisitDate: null,
        endVisitDate: null,
        departmentId: null,
        patientName: null,
        status: ''
      },
      // 表单参数
      form: {},
      // 预约信息
      formApp: {},
      // 状态数据字典
      statusOptions: [],
      // 科室列表
      departmentList: [],
      patientInfo: null,  // 患者信息
      appintmentInfo: null,
      // 关系类型映射
      relationTypes: {
        1: '父母',
        2: '子女',
        3: '夫妻',
        4: '本人',
        5: '朋友',
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('appointment_status').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('appointment_type').then(response => {
      this.typeOptions = response.data
    })
    // 获取科室列表
    this.getDepartmentList()
  },
  methods: {
    /** 查询科室列表 */
    getDepartmentList() {
      getdepartmentA().then(res => {
        this.option = res.data
      })
    },
    /** 查询预约挂号列表 */
    getList() {
      this.loading = true
      listAppointment(this.queryParams).then(response => {
        this.appointmentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        hospitalId: null,
        hospitalName: null,
        hospitalAddress: null,
        hospitalAddressName: null,
        departmentId: null,
        departmentName: null,
        doctorId: null,
        doctorName: null,
        jobTitle: null,
        jobTitleName: null,
        scheduleId: null,
        htime: null,
        period: null,
        registrationFee: null,
        visitDate: null,
        status: null,
        registrationType: null,
        cancelTime: null,
        cancelReason: null,
        cardNo: null
      }
      this.resetForm('form')
      // 重置科室和医生选项
      this.departmentOptions = []
    },
    /** 日期选择器变化事件 */
    handleDateChange(dates) {
      if (dates) {
        this.queryParams.beginVisitDate = dates[0]
        this.queryParams.endVisitDate = dates[1]
      } else {
        this.queryParams.beginVisitDate = null
        this.queryParams.endVisitDate = null
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      // 确保科室ID正确传递
      if (this.queryParams.departmentId === '') {
        this.queryParams.departmentId = null
      }
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.queryParams.departmentId = null  // 确保重置时清空科室ID
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 获取患者信息 */
    getPatientInfo(patientId) {
      getPatient(patientId).then(response => {
        console.log('患者信息数据:', response.data)
        this.patientInfo = response.data
        // 更新表单数据
        this.form = {
          ...this.form,
          name: this.patientInfo.name,
          card_no: this.patientInfo.card_no,
          id_card: this.patientInfo.id_card,
          phone: this.patientInfo.phone,
          address: this.patientInfo.address,
          relation: this.patientInfo.relation
        }
      })
    },
    /** 获取预约信息 */
    getAppointmentInfo(id) {
      getAppointment(id).then(response => {
        this.appintmentInfo = response
        console.log('预约信息数据:', response)
        this.formApp = {
          ...this.formApp,
          hospitalName: this.appintmentInfo.hospitalName,
          hospitalAddressName: this.appintmentInfo.hospitalAddressName,
          departmentName: this.appintmentInfo.departmentName,
          doctorName: this.appintmentInfo.doctorName,
          jobTitleName: this.appintmentInfo.jobTitleName,
          visitDate: this.appintmentInfo.visitDate,
          visitTime: this.appintmentInfo.visitTime,
          registrationTypeName: this.appintmentInfo.registrationType
        }

      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      console.log('查看预约详情:', row.id)
      this.form = row
      // 先清空患者信息
      this.patientInfo = null
      this.openView = true

      this.formApp = row
      // 获取预约信息详情
      this.appintmentInfo = null
      // 获取预约信息
      if (row.id) {
        this.getAppointmentInfo(row.id)
      }
      // 获取患者信息
      if (row.patientId) {
        this.getPatientInfo(row.patientId)
      }
    },
    viewReport() {
      this.$router.push({
        path: '/system/report',
        query: { appointmentId: this.form.id }
      })
    },
    /** 获取关系类型显示文本 */
    getRelationType(type) {
      return this.relationTypes[type] || '未知关系'
    }
  }
}
</script>

<style scoped>
.section-subtitle {
  font-size: 14px;
  color: #409EFF;
  margin-bottom: 20px;
  font-weight: bold;
}

.box-card {
  margin-bottom: 20px;
  border: 1px solid #EBEEF5;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-form-item span {
  color: #606266;
}

/* 科室下拉框样式 */
.department-select ::v-deep .el-input__inner {
  height: 32px;
  line-height: 32px;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
  padding-left: 15px;
  font-size: 14px;
}

.department-select ::v-deep .el-input__inner:hover {
  border-color: #409EFF;
}

.department-select ::v-deep .el-input__inner:focus {
  border-color: #409EFF;
}

/* 下拉选项样式 */
:deep(.department-select-dropdown) {
  .el-select-dropdown__item {
    height: 34px;
    line-height: 34px;
    padding: 0 15px;
    font-size: 14px;
  }

  .el-select-dropdown__item.selected {
    color: #409EFF;
    font-weight: bold;
  }

  .el-select-dropdown__item:hover {
    background-color: #f5f7fa;
  }
}

.patient-info-item {
  margin-bottom: 10px;
}

.patient-info-item label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.patient-info-item span {
  color: #333;
}

.detail-section {
  margin-bottom: 20px;

  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: #0066FF;
    margin-bottom: 20px;
    position: relative;
    padding-left: 12px;

    &:before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background-color: #0066FF;
      border-radius: 2px;
    }
  }

  .info-item {
    display: flex;
    margin-bottom: 16px;
    line-height: 32px;

    .label {
      color: #606266;
      min-width: 90px;
      margin-right: 8px;
    }

    .value {
      color: #333;
      flex: 1;
    }
  }
}

.el-dialog {
  .el-dialog__body {
    padding: 20px 30px;
  }
}
</style>
